package com.jajahome.feature.scheme;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jajahome.R;
import com.jajahome.application.JaJaHomeApplication;
import com.jajahome.base.BaseActivity;
import com.jajahome.constant.Constant;
import com.jajahome.feature.TencentWebV;
import com.jajahome.feature.scheme.adapter.SchemeItemListAdapter;
import com.jajahome.model.SchemeDetailModel;
import com.jajahome.model.SchemeModel;
import com.jajahome.model.VrItemListModel;
import com.jajahome.network.ApiImp;
import com.jajahome.network.ReqPage;
import com.jajahome.pop.PopShare;
import com.jajahome.util.StringUtil;
import com.jajahome.widget.ProgressWebView;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.squareup.picasso.Picasso;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.jajahome.constant.Constant.SHARE_SCHEME_URL;
import static com.jajahome.constant.Constant.VR_DETAIL_SEC;

/**
 * 方案
 */
public class SchemeDetailAct extends BaseActivity {

    @BindView(R.id.ibtn_back)
    ImageButton ibtnBack;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.progress_bar)
    ProgressWebView progressBar;
    @BindView(R.id.vr_items)
    LinearLayout vrItems;


    public static String VR_BEAN = "VrBean";
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_village)
    TextView tvVillage;
    @BindView(R.id.tv_house_type)
    TextView tvHouseType;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.tv_cost)
    TextView tvCost;
    @BindView(R.id.vr_image)
    ImageView vrImage;
    @BindView(R.id.scale_onclick)
    ImageView imgShare;
    private SchemeModel.DataBean.VrBean vrBean;
    private PopShare mPopShare;   //分享弹窗
    private IWXAPI mIwxapi;       //微信分享api
    private IWeiboShareAPI mIWeiboShareAPI;      //微博api
    private String mUrl;          //分享的url
    private SchemeDetailModel model;
    @Override
    protected int getViewId() {
        return R.layout.act_scheme_detail;
    }

    @Override
    protected void initEvent() {
        JaJaHomeApplication.getInstance().addActivity(SchemeDetailAct.this);
        ibtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        vrBean = (SchemeModel.DataBean.VrBean) getIntent().getSerializableExtra(VR_BEAN);
        textView2.setText("VR案例");
        progressBar.loadUrl(VR_DETAIL_SEC + vrBean.getId());
        String url = vrBean.getVr_image().getThumb();
        //如果连接不为空 加载到bitmap  计算视图大小
        if (url != null && !StringUtil.isEmpty(url)) {
            Picasso.with(this)
                    .load(url)
                    .placeholder(R.mipmap.ic_bottom_background)
                    .into(image);
        }
        imgShare.setBackgroundResource(R.mipmap.ic_bottom_share);
        imgShare.setVisibility(View.VISIBLE);
        getDetail();
        getVrItemList();
        //分享
        mIwxapi = WXAPIFactory.createWXAPI(mContext, Constant.WEICHAT_APP_ID, true);
        //新浪微博分享
        mIWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, Constant.WEIBO_APP_KEY);
        mIWeiboShareAPI.registerApp();    // 将应用注册到微博客户端
        imgShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(vrBean == null){
                    return;
                }
                if (mPopShare == null) {
                    mPopShare = new PopShare(SchemeDetailAct.this, mIwxapi, mIWeiboShareAPI, imgShare);
                    mPopShare.setmUrl(SHARE_SCHEME_URL + vrBean.getId());
                    mPopShare.setText(vrBean.getName());
                    mPopShare.setShowURI(vrBean.getVr_image().getSmall());
                }
                mPopShare.show();
            }
        });
    }

    /**
     * 获取套装详情信息
     */
    private void getDetail() {
        ReqPage.ContentBean contentBean = new ReqPage.ContentBean();
        contentBean.setId(vrBean.getId());
        ReqPage reqPage = new ReqPage();
        reqPage.setContent(contentBean);
        reqPage.setCmd(Constant.GET_ONE_VR);
        final Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(reqPage));
        mSubscription = ApiImp.get().getOneVr(requestBody).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<SchemeDetailModel>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(SchemeDetailModel model) {
                if (model != null && model.getData() != null) {
                    SchemeDetailAct.this.model = model;
                    setData(model.getData());
                }
            }
        });
    }

    /**
     * 获取套装详情信息
     */
    private void getVrItemList() {
        ReqPage.ContentBean contentBean = new ReqPage.ContentBean();
        contentBean.setId(vrBean.getId());
        ReqPage reqPage = new ReqPage();
        reqPage.setContent(contentBean);
        reqPage.setCmd(Constant.VR_SPACE_ITEMLIST);
        final Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(reqPage));
        mSubscription = ApiImp.get().getvVrSpaceItemlist(requestBody).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<VrItemListModel>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(VrItemListModel model) {
                if (model != null && model.getData() != null) {
                    setItemsDatas(model.getData().getVr_itemlist());
                }
            }
        });
    }

    private void setItemsDatas(List<VrItemListModel.DataBean.VrItemlistBean> vr_itemlist) {
        if (vr_itemlist != null) {
            boolean isFirstLine = true;
            for (VrItemListModel.DataBean.VrItemlistBean bean : vr_itemlist){
                if(bean.getItem() != null && bean.getItem().size() > 0) {
                    LinearLayout layout = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.view_vr_items, null);
                    TextView tvName = layout.findViewById(R.id.items_name);
                    tvName.setText(bean.getVr_space_name());
                    vrItems.addView(layout);
                    if(isFirstLine){
                        isFirstLine = false;
                        layout.findViewById(R.id.top_line).setVisibility(View.VISIBLE);
                    }else {
                        layout.findViewById(R.id.top_line).setVisibility(View.GONE);
                    }
                    RecyclerView recyclerView = (RecyclerView) layout.findViewById(R.id.recyclerView);
                    //解决数据加载不完的问题
                    recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
                    recyclerView.setNestedScrollingEnabled(false);
                    recyclerView.setHasFixedSize(true);
                    //解决数据加载完成后, 没有停留在顶部的问题
                    recyclerView.setFocusable(false);
                    SchemeItemListAdapter mAdapter = new SchemeItemListAdapter();
                    recyclerView.setAdapter(mAdapter);
                    mAdapter.addItems(bean.getItem());
                }
            }
        }
    }

    private void setData(SchemeDetailModel.DataBean data) {
        final SchemeDetailModel.DataBean.VrBean vr = data.getVr();
        if (!TextUtils.isEmpty(vr.getName())) {
            tvName.setVisibility(View.VISIBLE);
            tvName.setText(vr.getName());
        }
        if (!TextUtils.isEmpty(vr.getCity())) {
            tvCity.setVisibility(View.VISIBLE);
            tvCity.setText("城市：" + vr.getCity());
        }
        if (!TextUtils.isEmpty(vr.getVillage())) {
            tvVillage.setVisibility(View.VISIBLE);
            tvVillage.setText("楼盘：" + vr.getVillage());
        }
        if (!TextUtils.isEmpty(vr.getHouse_type())) {
            tvHouseType.setVisibility(View.VISIBLE);
            tvHouseType.setText("户型：" + vr.getHouse_type());
        }
        if (!TextUtils.isEmpty(vr.getArea())) {
            tvArea.setVisibility(View.VISIBLE);
            tvArea.setText("面积：" + vr.getArea());
        }
        if (!TextUtils.isEmpty(vr.getCost())) {
            tvCost.setVisibility(View.VISIBLE);
            tvCost.setText("软装花费：" + vr.getCost());
        }else {
            tvCost.setVisibility(View.GONE);
        }
        vrImage.setVisibility("1".equals(vr.getVr_flag()) ? View.VISIBLE : View.GONE);
        if (vr.getVr_url() != null) {
            vrImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TencentWebV.gotoH5(SchemeDetailAct.this, vr.getVr_url());
                }
            });

        }
    }

}
